package edu.upol.paradise.hypervisor.protocol;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

import org.apache.log4j.Logger;

import edu.upol.paradise.utils.HypervisorUtils;

public class TCPConnector implements Connector {
	static final Logger log = Logger.getLogger(TCPConnector.class);
	
	private Socket listeningSocket;
	
	public TCPConnector(Socket listeningSocket) throws Exception{
		this.listeningSocket = listeningSocket;
	}
	
	public TCPConnector(String addr, int port, int timeout) throws Exception {
		this.listeningSocket = new Socket();
		listeningSocket.connect(new InetSocketAddress(addr, port), timeout);
		this.listeningSocket.setSoTimeout(timeout);
	}

	public Packet accept() throws Exception {
		InputStream is = listeningSocket.getInputStream();
		
		byte[] header = new byte[10];
		HypervisorUtils.readFully(is, header, 0, 10);
		byte[] size = new byte[10];
		HypervisorUtils.readFully(is, size, 0, 10);
		
		return new Packet(header, size, is);
	}

	public void send(Packet packet) throws Exception {
		byte[] data = packet.toBytes();
		OutputStream os = listeningSocket.getOutputStream();
		HypervisorUtils.writeFully(os, data, 0, data.length);
	}

	public void terminate() throws Exception {
		listeningSocket.close();
	}

	
}
